package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xrit.sunnyday.dao.SetMealDao;
import com.xrit.sunnyday.entity.QueryPageBean;
import com.xrit.sunnyday.exception.SunnydayException;
import com.xrit.sunnyday.pojo.Setmeal;
import com.xrit.sunnyday.service.SetMealService;
import com.xrit.sunnyday.utils.QiNiuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service(interfaceClass = SetMealService.class)
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public PageInfo<Setmeal> findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        if(!StringUtils.isEmpty(queryPageBean.getQueryString())){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        List<Setmeal> list = setMealDao.findPage(queryPageBean.getQueryString());
        return new PageInfo<>(list);
    }

    @Override
    public void deleteById(Integer id) {
        int count = setMealDao.findOrderSetMealID(id);
        if(count>0){
            throw new SunnydayException("该套餐已被预约");
        }

        setMealDao.deleteSetMealGroupID(id);
        setMealDao.deleteById(id);
    }

    @Override
    public void add(Setmeal setmeal,Integer[] checkgroupIds) {
        setMealDao.add(setmeal);

        HashMap<String, Object> map = new HashMap<>();
        map.put("sid",setmeal.getId());
        map.put("gids",checkgroupIds);
        setMealDao.addSetmealGroupID(map);

        generateMobileStaticHtml();
    }

    @Override
    public HashMap<String,Object> findById(Integer id) {
        Setmeal setmeal = setMealDao.findById(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("setmeal",setmeal);
        map.put("domain", QiNiuUtils.DOMAIN);
        return map;
    }

    @Override
    public List<Integer> findSetmealGroupID(Integer id) {
        return setMealDao.findSetmealGroupID(id);
    }

    @Override
    public void update(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.update(setmeal);

        setMealDao.deleteSetMealGroupID(setmeal.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("sid",setmeal.getId());
        map.put("gids",checkgroupIds);
        setMealDao.addSetmealGroupID(map);
    }

    @Override
    public List<String> findImgs() {
        return setMealDao.findImgs();
    }

    @Override
    public Setmeal findDetailById(Integer id) {
        return setMealDao.findDetailById(id);
    }


    private void generateMobileStaticHtml() {
        try {
            //1.套餐列表静态页面
            generateSetmealListHtml();
            //2.套餐详情静态页面生成单个就行了，为了测试方便，生成所有的
            generateSetmealDetailHtml();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void generateSetmealListHtml() {
        //获取模板名称
        String templateName = "mobile_setmeal.ftl";
        //查询所有套餐
        List<Setmeal> setmealList = setMealDao.findAll();
        //拼接图片域名并返回
        setmealList.forEach(setmeal -> {
            setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
        });
        //创建数据
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList",setmealList);
        //拼接生成静态化页面的路径
        String setmealListFile = out_put_path+"mobile_setmeal.html";
        //调用封装的生成静态化页面的方法
        generateHtml(templateName,dataMap,setmealListFile);
    }

    private void generateSetmealDetailHtml() {
        //获取模板名称
        String templateName = "mobile_setmeal_detail.ftl";
        //查询所有套餐
        List<Setmeal> setmealList = setMealDao.findAll();
        for (Setmeal setmeal : setmealList) {
            //根据所有套餐ID查询所有套餐详情
            Setmeal setmealDetail = setMealDao.findDetailById(setmeal.getId());
            //拼接图片域名并返回
            setmealDetail.setImg(QiNiuUtils.DOMAIN+setmealDetail.getImg());
            //创建数据
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("setmeal",setmealDetail);
            //拼接生成静态化页面的路径
            String setmealDetailFile = out_put_path+"mobile_setmeal_"+setmealDetail.getId()+".html";
            //调用封装的生成静态化页面的方法
            generateHtml(templateName,dataMap,setmealDetailFile);
        }
    }


    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    @Value("${out_put_path}")
    private String out_put_path;
//     = "D:/IdeaProjects/A122_S3/sunnyday_parent/sunnyday_mobile/src/main/webapp/pages/"
    /**
     * 封装生成静态页面的方法
     */
    private void generateHtml(String templateName, Map<String,Object>dataMap,String outFileName){
        Configuration configuration = freeMarkerConfig.getConfiguration();
        //1.获取FreeMarker配置类
        BufferedWriter writer = null;
        try {
            //2.加载模板文件  -->已有，参数传进来
            Template template = configuration.getTemplate(templateName);
            //3.构建数据     -->已有，参数传进来
            //4.输出文件路径  -->文件名称已有，参数传进来
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFileName),"utf-8"));
            //5.将数据填充到模板
            template.process(dataMap,writer);
            //6.刷新缓冲流
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //7.关流
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
